package com.jerry.huihome.module.find.fragment;

import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jerry.huihome.R;
import com.jerry.huihome.base.BaseFragment;
import com.jerry.huihome.constant.Urls;
import com.jerry.huihome.module.find.adapter.DesignerWorksAdapter;
import com.jerry.huihome.module.find.entity.DesignerWorks;
import com.jerry.huihome.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2016/5/13.
 */
public class DesignerWorksFragment extends BaseFragment {

    private String designerid;
    @BindView(R.id.prf_work_select)
    PullToRefreshListView ptfWorksSelect;
    private String url;
    private List<DesignerWorks.BodyBean.WorkItemsBean> worksList = new ArrayList<>();
    private DesignerWorksAdapter adapter;
    private int pageIndex = 1;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_works_select;
    }

    @Override
    protected void getReqParams(Bundle bundle) {
        designerid = bundle.getString("designerid");
    }

    @Override
    protected void initViews() {
        ptfWorksSelect.getRefreshableView().setDivider(null);
        ptfWorksSelect.getRefreshableView().setSelector(android.R.color.transparent);
        ptfWorksSelect.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new DesignerWorksAdapter(getContext(),worksList);
        ptfWorksSelect.setAdapter(adapter);
        ptfWorksSelect.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                loadData();
            }
        });

    }

    @Override
    protected void loadData() {
        url = Urls.DESIGNER_WORKS_URL+designerid+"&pageIndex="+pageIndex;
        OkHttpUtils.get(url, new OkHttpUtils.OnGetDataListener() {
            @Override
            public void onResponse(String url, String data) {
                if (data != null){
                    if (pageIndex == 1){
                        adapter.clear();
                    }
                    Gson gson = new Gson();
                    DesignerWorks works = gson.fromJson(data,DesignerWorks.class);
                    worksList.addAll(works.getBody().getWorkItems());
                    adapter.notifyDataSetChanged();
                    ptfWorksSelect.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }
}
